/*
 * @Descripttion: 
 * @version: 
 * @Author: lily
 * @Date: 2021-05-21 14:35:09
 * @LastEditors: lily
 * @LastEditTime: 2021-05-21 17:42:47
 */
/*
 * @lc app=leetcode.cn id=54 lang=javascript
 *
 * [54] 螺旋矩阵
 */

// @lc code=start
/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
//  思想：
//  确认上下左右边界，逐行逐列进行访问
//  https://leetcode-cn.com/problems/spiral-matrix/solution/shou-hui-tu-jie-liang-chong-bian-li-de-ce-lue-kan-/

//  复杂度：O(mn) O(mn)

var spiralOrder = function (matrix) {
    if (matrix.length == 0) return []
    // 边界
    let top = 0, bottom = matrix.length - 1
    let left = 0, right = matrix[0].length - 1
    let res = []
    // 循环
    while (top <= bottom && left <= right) {
        for (let i = left; i <= right; i++) res.push(matrix[top][i])
        top++
        for (let i = top; i <= bottom; i++) res.push(matrix[i][right])
        right--
        // 防止上面的right减去之后又多余push
        if (top > bottom || left > right) break
        for (let i = right; i >= left; i--) res.push(matrix[bottom][i])
        bottom--
        for (let i = bottom; i >= top; i--) res.push(matrix[i][left])
        left++
    }
    return res
};


// @lc code=end

console.log(spiralOrder([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]))